﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Helpers;
using System.Web.Mvc;
using DistributeTransaction.DAL;
using DistributeTransaction.Models;
using DistributeTransaction.Utils;
using log4net;

namespace DistributeTransaction.Controllers
{
    public class ShoppingCartController : BaseController
    {
        private ILog log = LogManager.GetLogger(typeof(ShoppingCartController));
        private ShoppingCartRepository shoppingCartRepository;
        private OrderRepository orderRepository;

        public ShoppingCartController()
        {
            shoppingCartRepository = new ShoppingCartRepository(DBContext);
            orderRepository  = new OrderRepository(DBContext);
        }

        #region Shopping Cart View

        //
        // GET: /Cart/
        [HttpGet]
        public ViewResult Index()
        {
            string ids = TempData["data"] as string;
            if (!string.IsNullOrEmpty(ids))
            {
                shoppingCartRepository.UpdateShoppingCart(ParseProductIds(ids), CustomerId);
            }

            var dataset = shoppingCartRepository.GetShoppingCart(CustomerId);
            ViewBag.Amount = dataset.Sum(item => item.Quantity * item.UnitPrice);
            ViewBag.Summary = string.Format(CultureInfo.CurrentUICulture, "{0:C}", ViewBag.Amount);

            return View(dataset);
        }

        [HttpGet]
        public ActionResult Delete(int productID)
        {
            var dataset = shoppingCartRepository.GetShoppingCart(CustomerId);

            var item = dataset.FirstOrDefault(e => e.ProductID == productID); 
            return View(item);
        }

        [HttpGet]
        public ActionResult Edit(int productID)
        {
            var dataset = shoppingCartRepository.GetShoppingCart(CustomerId);
            var item = dataset.FirstOrDefault(e => e.ProductID == productID);
            return View(item);
        }

        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit(ShoppingCart sc)
        {
           shoppingCartRepository.Save(sc);            
           return RedirectToAction("Index", "ShoppingCart");
        }


        [HttpPost]
        [ActionName("Delete")]
        public ActionResult Delete()
        {
            string s = Request.QueryString.Get("ProductID");
            int productId;
            if (int.TryParse(s, out productId))
            {
                shoppingCartRepository.Remove(CustomerId, productId);
            }

            return RedirectToAction("Index", "ShoppingCart");
        }

        [HttpPost]
        //[ActionName("Index")]
        [AcceptSubmitType(Name = "Command", Type = "Empty Cart")]
        public ViewResult EmptyCart()
        {
            shoppingCartRepository.EmptyCart(CustomerId);
            return Index();
        }

        #endregion

        #region Payment Information View

        private decimal GetTotalAmount(FormCollection collection)
        {
            return decimal.Parse(collection.Get("Amount"));
        }


        [HttpPost]
        [ActionName("Index")]
        [AcceptSubmitType(Name = "Command", Type = "Check Out")]
        public ViewResult EditPaymentInformation(FormCollection collection)
        {
            //get total amount of shopping cart
            decimal totalAmount = GetTotalAmount(collection);

            Order order = orderRepository.GetOrderPayments(
                totalAmount,
                CustomerId
                );

            ViewBag.Amount = totalAmount;
            ViewBag.Summary = string.Format(
                CultureInfo.CurrentUICulture,
                "{0:C}",
                order.Current.Amount);  //current is left unpaid amount

            return View("EditPayment", order);
        }


        [HttpPost]
        [ActionName("EditPayment")]
        [AcceptSubmitType(Name = "Command", Type = "Continue")]
        public ViewResult Continue(Order order)
        {
            //set default value
            order = orderRepository.GetRecentlyOrder(CustomerId);
            order.OrderID = -1;//
            return View("EditShip", order);
        }

        [HttpPost]
        [ActionName("EditPayment")]
        [AcceptSubmitType(Name = "Command", Type = "Add Payment")]
        public ViewResult SavePayment(Order order, FormCollection collection)
        {
            decimal totalAmount = GetTotalAmount(collection);

            if (order.Current != null && order.Current.Amount > decimal.Zero)
            {
                PaymentRepository paymentRespository = new PaymentRepository(DBContext);

                paymentRespository.SaveCurrentPayment(order.Current, CustomerId);
                if (order.Payments == null)
                {
                    order.Payments = paymentRespository.GetTempPaymentForShoppingCart(CustomerId);
                }
                decimal summary = order.Payments.Sum(item => item.Amount);

                if (summary < totalAmount)
                {
                    return EditPaymentInformation(collection);
                }
                
            }

            return Continue(order);
        }

        [ActionName("DeletePayment")]
        public ViewResult DeletePayment(int id, FormCollection collection)
        {
            PaymentRepository paymentRespository = new PaymentRepository(DBContext);
            paymentRespository.DeletePayment(id, CustomerId);

            var dataset = shoppingCartRepository.GetShoppingCart(CustomerId);
            string amount = dataset.Sum(item => item.Quantity * item.UnitPrice).ToString("F4");

            collection.Add("Amount", amount);

            return EditPaymentInformation(collection);
        }

        #endregion

        [HttpGet]
        public JsonResult AddCard()
        {
            string html = this.RenderPartialView("AddCard", new CardInfo());
            return Json(new
            {
                Html = html,
                Message = string.Empty
            }, JsonRequestBehavior.AllowGet);
        }

        #region Ship Information View

        [HttpPost]
        [ActionName("EditShip")]
        [AcceptSubmitType(Name = "Command", Type = "Place Order")]
        public ActionResult CheckOut(Order order)
        {
            orderRepository.CheckOut(order, CustomerId);
            return RedirectToAction("Index", "Order");
        }

        [HttpPost]
        [ActionName("EditShip")]
        [AcceptSubmitType(Name = "Command", Type = "Cancel")]
        public ActionResult Cancel()
        {
            return RedirectToAction("Index", "ShoppingCart");
        }

        #endregion

    }
}